<template>
    <a-alert :show-icon="true" message="不填写名称将使用种子名进行识别" />
    <a-divider />
    <a-form :model="form" layout="inline" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
        <a-form-item label="名称" name="name">
            <a-input v-model:value="form.name" />
        </a-form-item>
        <a-form-item label="年份" name="year">
            <a-input v-model:value="form.year" />
        </a-form-item>
        <a-form-item>
            <a-button type="primary" @click="doRecognize" :loading="loading">识别</a-button>
        </a-form-item>
    </a-form>
    <a-divider v-show="recognized">
        共识别到{{ dataList.length }}条结果
    </a-divider>
    <MediaCardSet :data="dataList" @select="onSelect"/>
</template>
<script name="recognize" setup>
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Modal, message } from 'ant-design-vue';
import { ref, createVNode } from 'vue';

import MediaCardSet from '@/views/Index/media-card-set.vue'
import TorrentApi from '@/api/TorrentApi.js'

const props = defineProps(['id'])

const form = ref({})

const loading = ref(false)
const recognized = ref(false)
const dataList = ref([])

const doRecognize = () => {
    dataList.value = []
    loading.value = true
    recognized.value = false
    TorrentApi.recognize({ id: props.id, ...form.value }).then(response => {
        if (response.data.code === 1) {
            dataList.value = response.data.data;
        } else {
            message.error(`操作失败：${response.data.message}`);
        }
        recognized.value = true
    }).catch((error) => {
        message.error(`操作失败：${error.message}`);
    }).then(() => {
        loading.value = false
    })
}

const onSelect = (item) => {
    Modal.confirm({
        title: '确定识别为该媒体?',
        icon: createVNode(ExclamationCircleOutlined),
        content: `TMDB ID: ${item.id}, 名称: ${item.title}, 年份: ${item.year.split('-')[0]}`,
        onOk() {
          return new Promise((resolve, reject) => {
            TorrentApi.recognizeConfirm({ modelId: props.id, ...item }).then(response => {
                if (response.data.code === 1) {
                    cleanSearch();
                    emits('close', item)
                    message.success('操作成功');
                    resolve()
                } else {
                    message.error(`操作失败：${response.data.message}`);
                    reject()
                }
            }).catch((error) => {
                message.error(`操作失败：${error.message}`);
                reject()
            })
          });
        },
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        onCancel() {},
    });
}

const cleanSearch = () => {
    form.value = {}
    dataList.value = []
    recognized.value = false
}

const emits = defineEmits(['close'])
</script>